package com.wyj.wuliwuli.controller;

import com.wyj.wuliwuli.common.AjaxResult;
import com.wyj.wuliwuli.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Optional;

/**
 * @Version 1.0
 * @Description 文件接口
 */
@Api(tags = "文件")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/wuli-file")
@Slf4j
public class WuliFileController {

    @Value("${wuli.file.basedir:}")
    private String basedir;

    @ApiOperation(value = "上传文件")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        String filename = FileUtils.buildUniqueName(file.getOriginalFilename());
        try {
            FileUtils.upload(file.getBytes(), basedir, filename);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("文件上传出错:" + e.getMessage());
        }
        return AjaxResult.ok(filename);
    }

    @ApiOperation(value = "下载文件")
    @GetMapping("/download")
    public AjaxResult download(@ApiParam(name = "filename", value = "文件名") String filename, HttpServletResponse response) {
        try {
            // 设置响应头
//            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.setHeader("Content-Disposition", "inline; filename=" + filename);
            Optional<MediaType> optionalMediaType = MediaTypeFactory.getMediaType(filename);
            MediaType mediaType = optionalMediaType.orElse(MediaType.APPLICATION_OCTET_STREAM);
            response.setContentType(mediaType.toString());
            // 读取文件内容
            byte[] bytes = FileCopyUtils.copyToByteArray(new File(basedir + filename));
            // 写出文件内容
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.getMessage();
            return AjaxResult.fail("文件下载出错:" + e.getMessage());
        }
        return AjaxResult.of();
    }
}

